home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 127 / PC Guia 127.iso / Software / Produtividade / OpenOffice.org 2.0.1 / openofficeorg3.cab / pprint.py < prev    next >
Text File  |  2005-11-19  |  10KB  |  310 lines

  1. #  Author:      Fred L. Drake, Jr.
  2. #               fdrake@acm.org
  3. #
  4. #  This is a simple little module I wrote to make life easier.  I didn't
  5. #  see anything quite like it in the library, though I may have overlooked
  6. #  something.  I wrote this when I was trying to read some heavily nested
  7. #  tuples with fairly non-descriptive content.  This is modeled very much
  8. #  after Lisp/Scheme - style pretty-printing of lists.  If you find it
  9. #  useful, thank small children who sleep at night.
  10.  
  11. """Support to pretty-print lists, tuples, & dictionaries recursively.
  12.  
  13. Very simple, but useful, especially in debugging data structures.
  14.  
  15. Classes
  16. -------
  17.  
  18. PrettyPrinter()
  19.     Handle pretty-printing operations onto a stream using a configured
  20.     set of formatting parameters.
  21.  
  22. Functions
  23. ---------
  24.  
  25. pformat()
  26.     Format a Python object into a pretty-printed representation.
  27.  
  28. pprint()
  29.     Pretty-print a Python object to a stream [default is sys.sydout].
  30.  
  31. saferepr()
  32.     Generate a 'standard' repr()-like value, but protect against recursive
  33.     data structures.
  34.  
  35. """
  36.  
  37. import sys as _sys
  38.  
  39. from cStringIO import StringIO as _StringIO
  40.  
  41. __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
  42.            "PrettyPrinter"]
  43.  
  44. # cache these for faster access:
  45. _commajoin = ", ".join
  46. _id = id
  47. _len = len
  48. _type = type
  49.  
  50.  
  51. def pprint(object, stream=None):
  52.     """Pretty-print a Python object to a stream [default is sys.sydout]."""
  53.     printer = PrettyPrinter(stream=stream)
  54.     printer.pprint(object)
  55.  
  56. def pformat(object):
  57.     """Format a Python object into a pretty-printed representation."""
  58.     return PrettyPrinter().pformat(object)
  59.  
  60. def saferepr(object):
  61.     """Version of repr() which can handle recursive data structures."""
  62.     return _safe_repr(object, {}, None, 0)[0]
  63.  
  64. def isreadable(object):
  65.     """Determine if saferepr(object) is readable by eval()."""
  66.     return _safe_repr(object, {}, None, 0)[1]
  67.  
  68. def isrecursive(object):
  69.     """Determine if object requires a recursive representation."""
  70.     return _safe_repr(object, {}, None, 0)[2]
  71.  
  72. class PrettyPrinter:
  73.     def __init__(self, indent=1, width=80, depth=None, stream=None):
  74.         """Handle pretty printing operations onto a stream using a set of
  75.         configured parameters.
  76.  
  77.         indent
  78.             Number of spaces to indent for each level of nesting.
  79.  
  80.         width
  81.             Attempted maximum number of columns in the output.
  82.  
  83.         depth
  84.             The maximum depth to print out nested structures.
  85.  
  86.         stream
  87.             The desired output stream.  If omitted (or false), the standard
  88.             output stream available at construction will be used.
  89.  
  90.         """
  91.         indent = int(indent)
  92.         width = int(width)
  93.         assert indent >= 0
  94.         assert depth is None or depth > 0, "depth must be > 0"
  95.         assert width
  96.         self._depth = depth
  97.         self._indent_per_level = indent
  98.         self._width = width
  99.         if stream is not None:
  100.             self._stream = stream
  101.         else:
  102.             self._stream = _sys.stdout
  103.  
  104.     def pprint(self, object):
  105.         self._stream.write(self.pformat(object) + "\n")
  106.  
  107.     def pformat(self, object):
  108.         sio = _StringIO()
  109.         self._format(object, sio, 0, 0, {}, 0)
  110.         return sio.getvalue()
  111.  
  112.     def isrecursive(self, object):
  113.         return self.format(object, {}, 0, 0)[2]
  114.  
  115.     def isreadable(self, object):
  116.         s, readable, recursive = self.format(object, {}, 0, 0)
  117.         return readable and not recursive
  118.  
  119.     def _format(self, object, stream, indent, allowance, context, level):
  120.         level = level + 1
  121.         objid = _id(object)
  122.         if objid in context:
  123.             stream.write(_recursion(object))
  124.             self._recursive = True
  125.             self._readable = False
  126.             return
  127.         rep = self._repr(object, context, level - 1)
  128.         typ = _type(object)
  129.         sepLines = _len(rep) > (self._width - 1 - indent - allowance)
  130.         write = stream.write
  131.  
  132.         if sepLines:
  133.             if typ is dict:
  134.                 write('{')
  135.                 if self._indent_per_level > 1:
  136.                     write((self._indent_per_level - 1) * ' ')
  137.                 length = _len(object)
  138.                 if length:
  139.                     context[objid] = 1
  140.                     indent = indent + self._indent_per_level
  141.                     items  = object.items()
  142.                     items.sort()
  143.                     key, ent = items[0]
  144.                     rep = self._repr(key, context, level)
  145.                     write(rep)
  146.                     write(': ')
  147.                     self._format(ent, stream, indent + _len(rep) + 2,
  148.                                   allowance + 1, context, level)
  149.                     if length > 1:
  150.                         for key, ent in items[1:]:
  151.                             rep = self._repr(key, context, level)
  152.                             write(',\n%s%s: ' % (' '*indent, rep))
  153.                             self._format(ent, stream, indent + _len(rep) + 2,
  154.                                           allowance + 1, context, level)
  155.                     indent = indent - self._indent_per_level
  156.                     del context[objid]
  157.                 write('}')
  158.                 return
  159.  
  160.             if typ is list or typ is tuple:
  161.                 if typ is list:
  162.                     write('[')
  163.                     endchar = ']'
  164.                 else:
  165.                     write('(')
  166.                     endchar = ')'
  167.                 if self._indent_per_level > 1:
  168.                     write((self._indent_per_level - 1) * ' ')
  169.                 length = _len(object)
  170.                 if length:
  171.                     context[objid] = 1
  172.                     indent = indent + self._indent_per_level
  173.                     self._format(object[0], stream, indent, allowance + 1,
  174.                                  context, level)
  175.                     if length > 1:
  176.                         for ent in object[1:]:
  177.                             write(',\n' + ' '*indent)
  178.                             self._format(ent, stream, indent,
  179.                                           allowance + 1, context, level)
  180.                     indent = indent - self._indent_per_level
  181.                     del context[objid]
  182.                 if typ is tuple and length == 1:
  183.                     write(',')
  184.                 write(endchar)
  185.                 return
  186.  
  187.         write(rep)
  188.  
  189.     def _repr(self, object, context, level):
  190.         repr, readable, recursive = self.format(object, context.copy(),
  191.                                                 self._depth, level)
  192.         if not readable:
  193.             self._readable = False
  194.         if recursive:
  195.             self._recursive = True
  196.         return repr
  197.  
  198.     def format(self, object, context, maxlevels, level):
  199.         """Format object for a specific context, returning a string
  200.         and flags indicating whether the representation is 'readable'
  201.         and whether the object represents a recursive construct.
  202.         """
  203.         return _safe_repr(object, context, maxlevels, level)
  204.  
  205.  
  206. # Return triple (repr_string, isreadable, isrecursive).
  207.  
  208. def _safe_repr(object, context, maxlevels, level):
  209.     typ = _type(object)
  210.     if typ is str:
  211.         if 'locale' not in _sys.modules:
  212.             return `object`, True, False
  213.         if "'" in object and '"' not in object:
  214.             closure = '"'
  215.             quotes = {'"': '\\"'}
  216.         else:
  217.             closure = "'"
  218.             quotes = {"'": "\\'"}
  219.         qget = quotes.get
  220.         sio = _StringIO()
  221.         write = sio.write
  222.         for char in object:
  223.             if char.isalpha():
  224.                 write(char)
  225.             else:
  226.                 write(qget(char, `char`[1:-1]))
  227.         return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
  228.  
  229.     if typ is dict:
  230.         if not object:
  231.             return "{}", True, False
  232.         objid = _id(object)
  233.         if maxlevels and level > maxlevels:
  234.             return "{...}", False, objid in context
  235.         if objid in context:
  236.             return _recursion(object), False, True
  237.         context[objid] = 1
  238.         readable = True
  239.         recursive = False
  240.         components = []
  241.         append = components.append
  242.         level += 1
  243.         saferepr = _safe_repr
  244.         for k, v in object.iteritems():
  245.             krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
  246.             vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
  247.             append("%s: %s" % (krepr, vrepr))
  248.             readable = readable and kreadable and vreadable
  249.             if krecur or vrecur:
  250.                 recursive = True
  251.         del context[objid]
  252.         return "{%s}" % _commajoin(components), readable, recursive
  253.  
  254.     if typ is list or typ is tuple:
  255.         if typ is list:
  256.             if not object:
  257.                 return "[]", True, False
  258.             format = "[%s]"
  259.         elif _len(object) == 1:
  260.             format = "(%s,)"
  261.         else:
  262.             if not object:
  263.                 return "()", True, False
  264.             format = "(%s)"
  265.         objid = _id(object)
  266.         if maxlevels and level > maxlevels:
  267.             return format % "...", False, objid in context
  268.         if objid in context:
  269.             return _recursion(object), False, True
  270.         context[objid] = 1
  271.         readable = True
  272.         recursive = False
  273.         components = []
  274.         append = components.append
  275.         level += 1
  276.         for o in object:
  277.             orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
  278.             append(orepr)
  279.             if not oreadable:
  280.                 readable = False
  281.             if orecur:
  282.                 recursive = True
  283.         del context[objid]
  284.         return format % _commajoin(components), readable, recursive
  285.  
  286.     rep = `object`
  287.     return rep, (rep and not rep.startswith('<')), False
  288.  
  289.  
  290. def _recursion(object):
  291.     return ("<Recursion on %s with id=%s>"
  292.             % (_type(object).__name__, _id(object)))
  293.  
  294.  
  295. def _perfcheck(object=None):
  296.     import time
  297.     if object is None:
  298.         object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
  299.     p = PrettyPrinter()
  300.     t1 = time.time()
  301.     _safe_repr(object, {}, None, 0)
  302.     t2 = time.time()
  303.     p.pformat(object)
  304.     t3 = time.time()
  305.     print "_safe_repr:", t2 - t1
  306.     print "pformat:", t3 - t2
  307.  
  308. if __name__ == "__main__":
  309.     _perfcheck()
  310.